package com.hospital.wx.util;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Base64;

@Component
@Slf4j
public class WxMaUtil {
    
    @Autowired
    private WxMaService wxMaService;

    /**
     * 生成小程序码
     * @param page 小程序页面路径
     * @param scene 场景值，用于传递参数
     * @param width 码的宽度，单位px
     * @return 生成的小程序码图片
     */
    public BufferedImage generateMiniCode(String page, String scene, int width) {
        // 是否自动配置线条颜色
        boolean autoColor = false;

        // 是否需要透明底色
        boolean isHyaline = false;

        // 是否使用路径信息
        boolean usePathInfo = false;

        // 生成正式版小程序码
//        String envVersionRelease = "release";
        // 生成体验版小程序码
        String envVersionTrial = "trial";
        // 生成开发版小程序码
//        String envVersionDevelop = "develop";

        try {
            log.info("开始生成小程序码，页面路径：{}，场景值：{}，宽度：{}", page, scene, width);

            // 确保页面路径格式正确
            if (!page.startsWith("pages/")) {
                page = "pages/" + page;
            }

            WxMaCodeLineColor lineColor = new WxMaCodeLineColor("41", "121", "255");
            byte[] bytes = wxMaService.getQrcodeService()
                        .createWxaCodeUnlimitBytes(scene,
                                page,
                                usePathInfo,
                                envVersionTrial,
                                width,
                                autoColor,
                                lineColor,
                                isHyaline);

            if (bytes == null || bytes.length == 0) {
                throw new RuntimeException("生成的小程序码数据为空");
            }
            log.info("小程序码生成成功，数据大小：{} bytes", bytes.length);
            return ImageIO.read(new ByteArrayInputStream(bytes));
        } catch (Exception e) {
            throw new RuntimeException("生成小程序码失败", e);
        }
    }

    /**
     * 生成小程序码并返回Base64字符串
     */
    public String generateMiniCodeBase64(String page, String scene, int width) {
        try {
            BufferedImage image = generateMiniCode(page, scene, width);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", outputStream);
            byte[] imageBytes = outputStream.toByteArray();
            return "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            log.error("生成小程序码Base64失败", e);
            throw new RuntimeException("生成小程序码失败", e);
        }
    }
} 